package com.atguigu.juc.date928;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: shenhao
 * @CreatTime: 2024/9/28 18:12
 * @Version: 1.0
 * 同样的生产者消费者, 加1,减1,使用lock,condition.await和signalAll实现
 */
public class LockForExample {
    public static void main(String[] args) {
        Number number = new Number();
        Thread t1=new Thread(()->{
            for (int result = 0; result < 10; result++) {
                try {
                    number.add();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"生产者");
        t1.start();

        Thread t3=new Thread(()->{
            for (int result = 0; result < 10; result++) {
                try {
                    number.add();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"生产者2");
        t3.start();

        Thread t2=new Thread(()->{
            for (int result = 0; result < 10; result++) {
                try {
                    number.dec();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"消费者");
        t2.start();

        Thread t4=new Thread(()->{
            for (int result = 0; result < 10; result++) {
                try {
                    number.dec();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"消费者2");
        t4.start();
    }
}


class Number{
    private int num=0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();// 这里这个condition对象要写成成员变量!!!!!

    public  void add() throws InterruptedException {

        lock.lock();
        try {
            while (num!=0){
//            this.wait();
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"生产了"+(++num));
            condition.signalAll();
            //this.notifyAll();
        } finally {
            lock.unlock();
        }

    }

    public  void dec() throws InterruptedException {

        lock.lock();
        try {
            while (num==0){
//            this.wait();
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"消费了"+(--num));
            condition.signalAll();
            //this.notifyAll();
        } finally {
            lock.unlock();
        }
    }
}